package com.shu.socket.one2one;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author ssm
 * @version V1.0
 * @description:
 * @date 2019/2/20 19:40
 */

public class SocketServer {

  public static void main(String[] args) throws IOException {
    //
    ServerSocket servrSocket = null;

    try {
      servrSocket = new ServerSocket(8888);

      while (true) {
        Socket socket = servrSocket.accept();//阻塞
        new Thread(() -> {
          try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter writer = new PrintWriter(socket.getOutputStream());

            while (true) {
              String readLine = reader.readLine();
              if (readLine == null) {
                break;
              }
              System.out.println(readLine);
              writer.println("hello client");
              writer.flush();
            }
          } catch (IOException e) {
            e.printStackTrace();
          }
        }).start();
      }


    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (servrSocket != null) {
        servrSocket.close();
      }
    }

  }
}
